import React, { useState, useEffect } from 'react'
import { Space, Button, Image, Table, Tag, Pagination, message, Modal, Input, Avatar } from 'antd'
const { TextArea } = Input
import type { ColumnsType } from 'antd/es/table'
import { UserOutlined } from '@ant-design/icons'
import { httpNoteList, httpNoteCheck } from "@/request/api"
import placeholderImg from '@/assets/placeholder.jpg'
interface DataType {
  id: number
  title: string
  content: string
  carousel: string[]
  topic: string[]
  check: number
  user: {
    name: string
    avatar: string
  }
  createdAt: string
}
const View: React.FC = () => {
  const [notes, setNotes] = useState<any[]>([])
  const [page, setPage] = useState(1)
  const [content, setContent] = useState('')
  const [total, setTotal] = useState(0)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [nodeId, setNoteId] = useState<number>(0)
  const columns: ColumnsType<DataType> = [
    {
      title: '标题',
      dataIndex: 'title',
      width: 300,
    },
    {
      title: '封面图',
      dataIndex: 'carousel',
      render: (_, { carousel }) =>
        <Image
          width={200}
          height={100}
          src={carousel[0]}
          fallback={placeholderImg}
        />
    },
    {
      title: '话题',
      dataIndex: 'topic',
      render: (_, { topic }) => (
        <>
          {topic.map((item) => {
            return (
              <Tag key={item}>{item}</Tag>
            )
          })}
        </>
      ),
      width: 300
    },
    {
      title: '作者',
      dataIndex: 'user',
      render: (_, { user }) =>
        <>
          <Avatar src={user.avatar} icon={<UserOutlined />} />
          <span>{user.name}</span>
        </>,
      width: 200
    },
    {
      title: '审核',
      render: (_, record) => (
        record.check === 0 ?  <Tag color="warning">待审核</Tag> : (record.check === 1 ? <Tag color="success">已通过</Tag> : <Tag color="error">未通过</Tag>)
      ),
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          {record.check === 0 ?
            <><Button onClick={() => { checkNote(record.id, 1) }}>通过</Button><Button onClick={() => { checkNote(record.id, 2) }} danger>不通过</Button></>
            : (record.check === 1 ? <Button onClick={() => { setIsModalOpen(true), setNoteId(record.id) }} danger>不通过</Button> : <Button onClick={() => { checkNote(record.id, 1) }}>通过</Button>)}
        </Space>
      ),
    },
  ]
  // 切换页码
  const changPage = (page: number) => {
    setPage(page)
    fetchData(page)
  }
  // 请求数据
  const fetchData = async (page: number) => {
    const { code, data } = await httpNoteList({ page, size: 4 })
    if (code === 200) {
      setNotes(data.rows)
      setTotal(data.meta.count)
    }
  }
  // 审核
  const checkNote = async (noteId: number, check: number) => {
    const { code, message: msg, data } = await httpNoteCheck({ noteId, check, content })
    if (code === 200) {
      message.info('操作成功！')
      setContent('')
      setIsModalOpen(false)
      fetchData(page)
    }
  }

  useEffect(() => {
    fetchData(page)
  }, [])
  return (
    <>
      <Table columns={columns} pagination={false} rowKey={(record) => record.id} dataSource={notes} expandable={{
        expandedRowRender: (record) =>
          <>
            <div className='flex'><b>内容：</b><p className='whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: record.content }}></p></div>
            <div className='flex'><b>收藏：</b><span>{record.favorite}</span></div>
            <div className='flex'><b>点赞：</b><span>{record.like}</span></div>
            <div className='flex'><b>浏览：</b><span>{record.browse}</span></div>
            <div className='flex'><b>发布时间：</b><span>{record.createdAt}</span></div>
            <div className='flex'><b>图片：</b>
              {record.carousel.map((img: string | undefined) => (
                <Image className='px-2' width={40} height={40} key={img} src={img} />
              ))}
            </div>
          </>,
        rowExpandable: (record) => record.title !== 'Not Expandable'
      }} />
      <Pagination onChange={changPage} showSizeChanger={false} className='text-center my-6' pageSize={4} defaultCurrent={1} current={page} total={total} />
      <Modal title="审核不通过：" open={isModalOpen} onOk={() => { checkNote(nodeId, 2) }} onCancel={() => { setIsModalOpen(false), setContent('') }}>
        <TextArea value={content} onChange={(e) => { setContent(e.target.value) }} placeholder="请输入不通过的原因" />
      </Modal>
    </>
  )
}
export default View
